package com.huadao.cart_ccs.experiment.adjustWeight;

import com.huadao.cart_ccs.data.bo.CommandWord;
import com.huadao.cart_ccs.data.bo.ElectronicScaleBO;
import com.huadao.cart_ccs.modle.ElectronicScaleModle;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

public class AdjustWeightPresenter extends IAdjustWeightContract.IAdjustWeightPresenter {

    private ElectronicScaleModle electronicScaleModle;
    private double returnWeight1;
    private double returnWeight2;
    private int weightNumber;
    public AdjustWeightPresenter(IAdjustWeightContract.IAdjustWeightView baseView) {
        attachView(baseView);
        electronicScaleModle=new ElectronicScaleModle();
        EventBus.getDefault().register(this);
    }

    @Override
    void weight1() {
        weightNumber=1;
        electronicScaleModle.weight();
    }

    @Override
    void weight2() {
        weightNumber=2;
        electronicScaleModle.weight();
    }

    @Override
    void adjust() {
        weightNumber=0;
        if(returnWeight1==returnWeight2){
            baseView.showDialogMessage(null,"两个称重值一样，无法校准！");
            return;
        }
        int realWeight1=baseView.getRealWeight1();
        int realWeight2=baseView.getRealWeight2();
        double a=(realWeight1-realWeight2)/(returnWeight1-returnWeight2);
        double b=realWeight1-a*returnWeight1;
        baseView.onAdjust(a,b);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(ElectronicScaleBO event) {
        if (event.getCommondWord() == CommandWord.readSucc[0]) {
            if(weightNumber==1){
                returnWeight1=  event.getWeight();
                baseView.onWeight1(returnWeight1);
            }else if(weightNumber==2){
                returnWeight2=  event.getWeight();
                baseView.onWeight2(returnWeight2);
            }
        }else {
            baseView.showToast(event.toString());
        }
    }

}
